const handleMirror = (imageElement: HTMLImageElement): Promise<File> =>
    new Promise((resolve, reject) => {
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');

        if (!ctx) {
            reject(new Error('无法获取 canvas 上下文'));
            return;
        }

        // 设置 canvas 尺寸为图片原始尺寸
        canvas.width = imageElement.naturalWidth || imageElement.width;
        canvas.height = imageElement.naturalHeight || imageElement.height;

        // 镜像翻转绘制
        ctx.translate(canvas.width, 0);
        ctx.scale(-1, 1);
        ctx.drawImage(imageElement, 0, 0);

        // 将 canvas 转为 Blob，再转为 File
        canvas.toBlob((blob) => {
            if (blob) {
                const file = new File([blob], 'mirrored-image.png', {
                    type: 'image/png',
                });
                resolve(file);
            } else {
                reject(new Error('生成 Blob 失败'));
            }
        }, 'image/png');
    });

export default class EImageUtil {
    static mirror(img: string | HTMLImageElement): Promise<File> {
        return new Promise((resolve, reject) => {
            if (typeof img === 'string') {
                let imageElement = new Image();
                imageElement.crossOrigin = 'Anonymous'; // 允许跨域请求
                imageElement.src = img;

                imageElement.onload = () => {
                    handleMirror(imageElement).then(resolve).catch(reject);
                };

                imageElement.onerror = (error) => {
                    reject(error);
                };
            } else {
                handleMirror(img).then(resolve).catch(reject);
            }
        });
    }
}
